using System.Collections.Generic;

namespace System.Utility
{
    public class IocContainer
    {
        private Dictionary<string, Type> cache;

        private static IocContainer @default = new IocContainer();

        public static IocContainer Default
        {
            get { return IocContainer.@default; }
        }

        public IocContainer()
        {
            this.cache = new Dictionary<string, Type>();
        }

        public void Register<T>(Type implement)
        {
            if (implement == null)
            {
                throw new ArgumentNullException("implement");
            }
            Type @abstract = typeof(T);
            if (!@abstract.IsAssignableFrom(implement))
            {
                throw new ArgumentException("不存在继承关系!", "implement");
            }
            this.cache.Add(@abstract.FullName, implement);
        }

        public void Register<TAbstract, TImplement>()
        {
            this.Register<TAbstract>(typeof(TImplement));
        }

        public T Resolve<T>() where T : class
        {
            Type result;
            string key = typeof(T).FullName;
            if (!this.cache.TryGetValue(key, out result))
            {
                throw new ArgumentException("未注册类型!", key);
            }
            return Activator.CreateInstance(result) as T;
        }
    }
}